<?php


namespace App\Services;

use App\Models\Site;
use App\Supports\Curl;

class SiteProductCategorySyncService
{
    public static function site_cate_sync($siteid)
    {
        $site = Site::where('id', $siteid)->first();
        $domian = $site->domian;
        $apipass = $site->apipass;
        $result = self::synccate($domian,$apipass);
        if ($site&&$result) {
            foreach ($result['data'] as &$k){
                $k['value']=str_replace("+","-",$k['value']);
                $k['text']=str_replace("+"," ",$k['value']);
            }
            return json_encode($result['data']);
        } else {
            return 'error link';
        }
    }

    public static function is_closed($siteid)
    {
        $is_sync = Site::where('id', $siteid)->first()->is_sync;
        return intval($is_sync) == 1 ? true : false;
    }

    public static function synccate($domian,$apipass)
    {
        $param = [];
        $param["action"] = "category";
        $result = self::sendrequest($param,$domian,$apipass);
        $result = json_decode($result, true);
        return $result;
    }

    public static function checklink($url,$apipass)
    {

        $reuslt=self::sendrequest($param = [],$url,$apipass);
        if($reuslt=="dreamisok")
        {
            return true;
        }
    }

    public static function sendrequest($param = [],$domian,$apipass)
    {

        if (!isset($param["action"])) {
            $action = "test";
        } else {
            $action = $param["action"];
            unset($param["action"]);
        }
        $url = $domian . "/?__kds_flag=" . $action;
        $param["kds_password"] = $apipass;

        switch ($action) {
            case "test":
                break;
            case "category":
            case "addproduct":
            case "delproduct":
            case "sync_enquiry":
                    if (!self::checklink($domian,$apipass)) {
                    return "broken link";
                }
                break;
            default:
                return false;
        }
        return Curl::curl($url, $param,true);
    }
}
